<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\RoomUser;
use wyiyun\Common;
use think\Request;
use think\Db;
use think\Exception;

/**
 *
 * ription 教室用户控制器
 *
 * @author 时
 */
class RomUser extends  Controller
{

    protected $user_id;

    protected $room_id;
    private $arr=array();

    /**
     * ription 查询用户的状态返回相应的状态
     *
     * @author sj
     * @version 1.0
     */
    // public function __construct(){
    // self::$appkey=config('appkey');
    // self::$appsercret=config('appsercret');
    // self::$wyiyun=new Common(self::$appkey,self::$appsercret);
    // }
    // 这里注意的是用户账号必须注册 必须是登录 必须这个用户成功连接教室的时候才发送请求
    public function getUserStatus()
    {
        $RoomUser = new RoomUser();
        $res = $RoomUser->getstatusById('1', '22');
        // 查询用户状态为 false 意味着用户没有进入过改房间 添加用户房间 并且成功返回输出json
        if ($res === 'false') {
            $result = $RoomUser->add_room_user('233', '2');
            if ($result === 'sucess') {
                var_dump('{"status":"sucess"}');
            } else {
                var_dump('{"status":"failed"}');
            }
        } elseif ($res === 0) {
            // 如果用户状态为0 意味着这个用户已经进入该房间并且未进行支付
            echo '{"msg":"user not appliy","code":"414"}';
            // 返回给前端 前端根据返回的结果 进行提示用户进行支付页面 如果用户拒绝支付 发出请求踢出用户
        } else {
            echo '{"msg":"the account already appliy","code":"200"}';
            // 前端获得msg 就可以让其进行进入房间观看
        }
    }

    /**
     * 踢人
     */
    public function kicking()
    {}

    /**
     *
     * @param string $room_id
     *            教室房间号
     * @return array $result 返回教室详细信息
     */
    public function onlie_fetch_room($room_id = "")
    {
        if (Request::instance()->isGet()) {
            return view('select');
        } else {
            $wyiyun = new Common(config('appkey'), config('appsecret'));
            $room_id = input('post.room_id');
            // $options=array('name'=>'ss','announcement'=>'','broadcasturl'=>'','creator'=>'');
            $res = $wyiyun->FetchChatInfos($room_id);
            $result = json_decode($res, true);
            // var_dump($result);
            // die;
            $this->assign('roominfo', $result['chatroom']);
            return view('room_info');
        }
    }

    /**
     *
     * @param string $room_id            
     * @return null;
     *
     */
    public function select($room_id = "")
    {
        if (Request::instance()->isGet()) {
            return view('select2');
        } else {
            $wyiyun = new Common(config('appkey'), config('appsecret'));
            $room_id = input('post.room_id');
            // $options=array('name'=>'ss','announcement'=>'','broadcasturl'=>'','creator'=>'');
            $res = $wyiyun->FetchChatInfos($room_id);
            $result = json_decode($res, true);
            // var_dump($result);
            // die;
            $this->assign('roominfo', $result['chatroom']);
            return view('room_update');
        }
    }

    /**
     * 更新聊天室
     */
    public function update_chatroom()
    {
        if (Request::instance()->isPost()) {
            
            $roomid = input('post.room_id');
            $name = input('post.name');
            $announcement = input('post.announcement');
            $broadcasturl = input('post.broadcasturl');
            $ext = input('post.ext');
            // $needNotify="true";
            // $notifyExt=input('post.notifyExt');
            $data = array(
                'roomid' => $roomid,
                'name' => $name,
                'announcement' => $announcement,
                'broadcasturl' => $broadcasturl,
                'ext' => $ext
            );
            $wyiyun = new Common(config('appkey'), config('appsecret'));
            $data = $wyiyun->UpdateChatRom($data);
            $data = json_decode($data, true);
            if ($data['code'] == 200) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        }
    }

    /**
     * ription: 用于查询房间创建者的用户ID
     * 
     * @param string $room_id
     *            教室id
     * @return string $info 教室创建者的用户名
     */
    public function fetch_chatroom_info($room_id = "10865520")
    {
        $wyiyun = new Common(config('appkey'), config('appsecret'));
        // $options=array('name'=>'ss','announcement'=>'','broadcasturl'=>'','creator'=>'');
        $res = $wyiyun->FetchChatInfos($room_id);
        $result = json_decode($res, true);
        $acid = "";
        if (isset($result)) {
            $acid = $result['chatroom']['creator'];
        } else {
            return '{"chatroom is not exstits}';
        }
        $info = Db::table('zx_wuser')->field('user_id')
            ->where('acid', $acid)
            ->find();
        if (isset($info)) {
            return json_encode($info);
        }
    }

    /**
     *
     * @return \think\response\View
     */
    public function toggleCloseStat()
    {
        if (Request::instance()->isGet()) {
            return view("toggleCloseStat");
        } else {
            $wyiyun = new Common(config('appkey'), config('appsecret'));
            $options = array(
                'roomid' => input('post.room_id'),
                'operator' => input('post.operator'),
                'valid' => input('post.valid')
            );
            
            $res = $wyiyun->closestate($options);
            $res_arr = json_decode($res, true);
            if ($res_arr['code'] == 200) {
                $this->success('房间操作成功');
            } else {
                $this->error('请勿重复修改房间状态');
            }
        }
    }

    /**
     * ription:设置聊天室内用户角色
     * 
     * @return null
     */
    public function setMemberRole()
    {
        if (Request::instance()->isGet()) {
            return view();
        } else {
            $data = array();
            $data['roomid'] = input('post.roomid');
            $data['operator'] = input('post.operator');
            $data['target'] = input('post.target');
            $data['opt'] = input('post.opt');
            $data['optvalue'] = input('post.optvalue');
            $wyiyun = new Common(config('appkey'), config('appsecret'));
            $res = $wyiyun->MemberRole($data);
            $result = json_decode($res, true);
            if ($result['code'] == 200) {
                $this->success('设置用户权限成功');
            } elseif ($result['desc'] == "duplicate operation on MANAGER!") {
                $this->error('已经设置过权限,请勿重复添加');
            } else {
                $this->error('设置用户角色失败');
            }
        }
    }

    /**
     * ription：查询教室请求地址
     * 
     * @param array $options
     *            查询教室地址数组
     * @return string 教室地址
     */
    public function chatroomRequestAddr()
    {
        if (Request::instance()->isGet()) {
            return view();
        } else {
            $options = array();
            $options['roomid'] = input('post.room_id');
            $user_id = input('post.user_id');
            $acid = Db::table('zx_wuser')->field('acid')
                ->where('user_id', $user_id)
                ->find();
            $options['accid'] = $acid['acid'];
            $clienttype = input('post.clienttype');
            $options['clienttype'] = $clienttype;
            
            $wyiyun = new Common(config('appkey'), config('appsecret'));
            $res = $wyiyun->requestAddr($options);
            $result = json_decode($res, true);
            if ($result['code'] == 200) {
                // 这里是前端的返回结果
                return '{"address":"' . $result['addr']['0'] . '"}';
            } else {
                $this->error('查询地址失败');
            }
        }
    }

    /**
     * 发送聊天室消息
     */
    public function sendMsg()
    {
        if (Request::instance()->isGet()) {
            return view();
        } else {
            $options = array();
            $options['roomid'] = input('post.room_id');
            $options['fromAccid'] = input('post.fromAccid');
            $options['msgType'] = input('post.msgType');
            $options['attach'] = input('post.attach');
            $wyiyun = new Common(config('appkey'), config('appsecret'));
            $res = $wyiyun->sendMsg($options);
            $result = json_decode($res, true);
            if ($result['code'] == 200) {
                $this->success('信息发送成功');
            } else {
                // return '{"status":"failed"}';
                $this->error('信息发送失败');
            }
        }
    }

    /**
     * 设置临时禁言状态
     */
    public function temporaryMute()
    {
        if (Request::instance()->isGet()) {
            return view();
        } else {
            $options = array();
            $options['roomid'] = input('post.room_id');
            $options['operator'] = input('post.operator');
            $options['target'] = input('post.target');
            $options['muteDuration'] = input('post.muteDuration');
            $options['notifyExt'] = input('post.notifyExt');
            $wyiyun = new Common(config('appkey'), config('appsecret'));
            $res = $wyiyun->temporaryMute($options);
            $result = json_decode($res, true);
            if ($result['code'] == 200) {
                $this->success('设置禁言成功', 'admin/rom/show');
                // return $res;
            } else {
               //return '{"status":"failed"}';
               $this->error('禁言失败');
           }
            
       }
   }
   //将聊天室整体禁言
   public function muteRoom()
   {
       if(Request::instance()->isGet()&&!Request::instance()->isAjax())
       {
           return view();
       }else 
       {
           $options=array();
           $options['roomid']=input('post.room_id');
           $options['operator']=input('post.operator');
           $options['mute']=input('post.mute');
           $wyiyun=new Common(config('appkey'), config('appsecret'));
         try {
             $res=$wyiyun->muteRoom($options);
             $res_arr=json_decode($res,true);
             if($res_arr['code']=='200')
             {
             $this->success('聊天室整体操作成功');    
             }elseif($res_arr['desc']=="check ".$options['operator'])
             {
               $this->error('请填写正确的房间创建者');
             }elseif($res_arr['desc']=='chatroom mute stat already is true') {
                $this->error('房间已经是禁言状态,请勿重复操作');
             }else {
                 $this->error('请输入正确的房间号');
             }
         }catch (Exception $e){
             
         }
           
       }
       
   }
   /**
    * 分页获取成员列表
    */
   public function membersByPage()
   {
       if(Request::instance()->isGet()&&!Request::instance()->isAjax())
       {
           return view();
       }else 
       {
          $options=array();
          $options['roomid']=input('post.room_id');
          $options['type']=input('post.type');
          $options['endtime']=0;
          $options['limit']=input('post.limit');
        
          $wyiyun=new Common(config('appkey'), config('appsecret'));
           try
           {
               $res=$wyiyun->membersByPage($options);
               $res_arr=json_decode($res,true);
               if($res_arr['code']=='200')
               {
                  var_dump($res); 
               }elseif($res_arr['desc']=="parameter 'roomid' should be provided of type long"){
                   $this->error('请输入教室ID');
               }elseif ($res_arr['desc']=="parameter 'roomid' no exist or invalid, roomid=".$options['roomid']){
                   $this->error('请输入正确的教室ID');
               }elseif ($res_arr['desc']=="parameter 'type' should be provided of type long"){
                   $this->error('请填写查询类型');
               }
           }catch (Exception $e)
           {
               print $e->getMessage();
           }
       }
   }
   /**
    * 批量获取在线成员信息
    */
   public function queryMembers()
   {
    
       if(Request::instance()->isGet()&&!Request::instance()->isAjax())
       {
           
      
           return view();
         
       }else
       {
           $options=array();
           $options['roomid']=input('post.room_id');
           $users=Db::table('zx_wuser')->field('acid')->select();
           $arr=array();
          foreach ($users as $user)
          {
             $arr[]=$user['acid'];
          }
//           $test=array();
//           $test[]='179';
           $json=json_encode($arr);
           $options['accids']=$json;
           $wyiyun=new Common(config('appkey'), config('appsecret'));
           try
           {
               $res=$wyiyun->queryMembers($options);
               $res_arr=json_decode($res,true);
             
               if($res_arr['code']=='200')
               {
                   var_dump($res);
               }elseif($res_arr['desc']=="parameter 'roomid' should be provided of type long"){
                   $this->error('请输入教室ID');
               }elseif ($res_arr['desc']=="parameter 'roomid' no exist or invalid, roomid=".$options['roomid']){
                   $this->error('请输入正确的教室ID');
               }elseif ($res_arr['desc']=="parameter 'type' should be provided of type long"){
                   $this->error('请填写查询类型');
               }
           }catch (Exception $e)
           {
               print $e->getMessage();
           }
       }
   }
   /**
    * 变更聊天室内的角色信息
    */
    public function updateMyRoomRole()
    {
        if(Request::instance()->isGet()&&!Request::instance()->isAjax())
        {
           return view(); 
        }else {
            //post数组传递
          $wyiyun=new Common(config('appkey'), config('appsecret'));
          $res=$wyiyun->updateMyRoomRole($_POST);
          $res_arr=json_decode($res,true);
          if($res_arr['code']=="200"){
              $this->success('操作成功');
          }
          
        }
    }
    /**
     * 从队列中取出元素
     * 接口描述
     * 从队列中取出元素
     */
    public function queuePoll()
    {
        if(Request::instance()->isGet()&&!Request::instance()->isAjax())
        {
            return view();
        }else 
        {
               $wyiyu=new Common(config('appkey'), config('appsecret'));
           try 
           {
               $res=$wyiyu->queuePoll($_POST);
               $res_arr=json_decode($res,true);
               if($res_arr['code']=='200')
               {
               $this->success('取出队列元素成功');    
               }else 
               {
               $this->error("操作失败");    
               }
           }catch (Exception $e)
           {
               print ($e->getMessage());
           }
        }
    }
    /**
          初始化队列
     */
    public function queueInit()
    {
        if(Request::instance()->isGet()&&!Request::instance()->isAjax())
        {
            return view();
        }else
        {
            $wyiyu=new Common(config('appkey'), config('appsecret'));
            try
            {
                $res=$wyiyu->queueInit($_POST);
                $res_arr=json_decode($res,true);
                if($res_arr['code']=='200')
                {
                $this->success('队列初始化成功');    
                }else
                {
                    $this->error($res);
                }
            }catch (Exception $e)
            {
                print ($e->getMessage());
            }
        }
    }
    /**
    排序列出队列中所有元素
     */
    public function queueList()
    {
        if(Request::instance()->isGet()&&!Request::instance()->isAjax())
        {
            return view();
        }else
        {
            $wyiyu=new Common(config('appkey'), config('appsecret'));
            try
            {
                $res=$wyiyu->queueList($_POST);
                $res_arr=json_decode($res,true);
                if($res_arr['code']=='200')
                {
                    $this->success('队列初始化成功');
                }else
                {
                    var_dump($res);
                }
            }catch (Exception $e)
            {
                print ($e->getMessage());
            }
        }
    }
    /**
     删除清理整个队列
     */
    public function queueDrop()
    {
        if(Request::instance()->isGet()&&!Request::instance()->isAjax())
        {
            return view();
        }else
        {
            $wyiyu=new Common(config('appkey'), config('appsecret'));
            try
            {
                $res=$wyiyu->queueList($_POST);
                $res_arr=json_decode($res,true);
                if($res_arr['code']=='200')
                {
                    $this->success('队列初始化成功');
                }else
                {
                    var_dump($res);
                }
            }catch (Exception $e)
            {
                print ($e->getMessage());
            }
        }
    }
    /**
    单聊云端历史消息查询
     */
    public function querySessionMsg()
    {
        if(Request::instance()->isGet()&&!Request::instance()->isAjax())
        {
            return view();
        }else
        {
            $wyiyu=new Common(config('appkey'), config('appsecret'));
            try
            {
                $res=$wyiyu->queueList($_POST);
                $res_arr=json_decode($res,true);
                if($res_arr['code']=='200')
                {
                    $this->success('队列初始化成功');
                }else
                {
                    var_dump($res);
                }
            }catch (Exception $e)
            {
                print ($e->getMessage());
            }
        }
    }
}